package com.tg.app.activity.device.add;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.alibaba.fastjson.JSONObject;
import com.appbase.custom.config.ApiUrl;
import com.base.BaseActivity;
import com.tange.base.toolkit.StringUtils;
import com.tange.base.toolkit.TGThreadPool;
import com.tange.module.camera.hub.CameraHub;
import com.tange.module.core.wifi.scan.BizWiFiUtil;
import com.tange.module.core.wifi.scan.WiFiScanManager;
import com.tange.module.core.wifi.scan.WifiToolkit;
import com.tg.app.R;
import com.tg.app.TGSdk;
import com.tg.app.activity.device.DeviceListActivity;
import com.tg.app.helper.ActivityHelper;
import com.tg.app.listener.OnAddDeviceListener;
import com.tg.app.report.DeviceAddReport;
import com.tg.app.report.DeviceAddReportBean;
import com.tg.app.util.LogUtils;
import com.tg.appcommon.android.PermissionUtil;
import com.tg.appcommon.android.TGAlertDialog;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.sdk.TGMessageType;
import com.tg.data.helper.DeviceTypeHelper;

import java.util.List;

/**
 * TODO: 拆
 */
public class AddFragmentTabActivity extends BaseActivity implements OnAddDeviceListener {
    public static final int PERMISSON_REQUESTCODE = 999;
    private static final String TAG = "AddFragmentTabActivity";
    public static final String EXT_DEVICE_ADD_TYPE = "ext_add_device_type";
    public static final String EXT_DEVICE_ADD_UUID = "ext_add_device_uuid";
    public static final String EXT_DEVICE_ADD_QRCODE_SUCCEDD_ID = "ext_add_device_succeed_ID";
    public static final int DEVICE_ADD_TYPE_QRCODE = 0x01;
    public static final int DEVICE_ADD_TYPE_AP = 0x02;
    public static final int DEVICE_ADD_TYPE_LAN = 0x03;
    public static final int DEVICE_ADD_TYPE_AP_LOCAL = 0x04;
    public static final int DEVICE_ADD_TYPE_QRCODE_SCAN = 0x05;
    public static final int DEVICE_ADD_TYPE_BATTERY = 0x06;
    public static final int DEVICE_ADD_4G_CAR = 0x07;
    public static final int DEVICE_ADD_4G_CAR_SEARCH = 0x08;
    public static final int TYPE_QR_CODE = 0x10;
    public static final int TYPE_AP = 0x11;
    public static final int TYPE_SCAN_QRCODE = 0x12;
    private int originType;
    private ImageButton backButton;
    private String uuid;
    private long deviceId;
    public static final int ERROR_NORMAL = 0;
    public static final int ERROR_SIM_NORMAL = 2;
    public static final int ERROR_SIM_NONE_DATA = 1;
    public static final String EXT_SIM_FREE_COMBO = "sim_NOTICE";
    private int mFreeCombo = 1;
    private String mThirdPartyUUID = "";
    private final static String[] needQrcodeScanPermissions = {
            Manifest.permission.CAMERA,
            Manifest.permission.VIBRATE
    };


    public ImageButton getBackButton() {
        return backButton;
    }

    @Override
    public void onClickTimeout(){

    }

    @Override
    public void onSet4GDeviceName(long device, String uuid, int authStatus, String iccId,int freeCombo) {


    }

    @Override
    public boolean shouldSetStatusBarColor() {
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_add_fragment_tab);
        hideActionBar();
        originType = getIntent().getIntExtra(EXT_DEVICE_ADD_TYPE, 0);
        mThirdPartyUUID = getIntent().getStringExtra(EXT_DEVICE_ADD_UUID);
        TGLog.d(TAG, "orginType = " + originType);
        if (savedInstanceState == null) {
            if (originType == DEVICE_ADD_4G_CAR||originType == DEVICE_ADD_TYPE_QRCODE_SCAN||originType == DEVICE_ADD_4G_CAR_SEARCH) {
                Add4gCarGuideFragment add4gCarGuideFragment = Add4gCarGuideFragment.newInstance(originType);
                add4gCarGuideFragment.setOnAddDeviceListener(this);
                getSupportFragmentManager().beginTransaction()
                        .add(R.id.fl_lan_add_container, add4gCarGuideFragment,
                                "BatteryGuideFragment").commit();
            } else {
                AddGuideFragment preparationBeforeAddFragment = AddGuideFragment.newInstance(originType);
                preparationBeforeAddFragment.setListener(this);
                getSupportFragmentManager().beginTransaction()
                        .add(R.id.fl_lan_add_container, preparationBeforeAddFragment,
                                "AddGuideFragment").commit();
            }

        }

        initView();
        LogUtils.matTrackCustomKVEvent(this, "device_add", "ADW");
    }

    private void showDialog() {
        new TGAlertDialog(this).builder().setTitle(getString(R.string.notice_4g_car)).setMessage(R.string.confirm_to_add_4g_car)
                .setPositiveButton(getString(R.string.confirm), v -> {

                    if (TGSdk.getInstance().isThirdPartyApp()) {
                        JSONObject jsonObject = new JSONObject();
                        try {
                            jsonObject.put(TGSdk.KEY_UUID, getIntent().getStringExtra(ApiUrl.DEVICE_UUID));
                            jsonObject.put(TGSdk.KEY_NAME, "Cancel");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        String param = jsonObject.toJSONString();
                        TGLog.d("param = " + param);
                        TGSdk.getInstance().notifyThirdPartyApp(TGMessageType.MSG_CANCEL_DEVICE_ADD, param);
                    } else {
                        finish();
                    }

                }).setNegativeButton(getString(R.string.cancle_add_4g_car), v -> {

                }).show();
    }

    private Fragment getVisibleFragment() {
        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        for(Fragment fragment:fragments)
        {
            if(fragment != null && fragment.isVisible())
                return fragment;
        }
        return null;
    }


    @Override
    protected void initView() {
        backButton = findViewById(R.id.back_toolbar_btn);
        backButton.setOnClickListener(view -> {
            if (originType == DEVICE_ADD_4G_CAR||originType == DEVICE_ADD_TYPE_QRCODE_SCAN||originType == DEVICE_ADD_4G_CAR_SEARCH) {
                Fragment fragment = getVisibleFragment();
                if (fragment instanceof CarDeviceProgressFragment) {
                    showDialog();
                    return;
                }
            }
            finish();
        });
        if (originType == DEVICE_ADD_TYPE_BATTERY || originType == DEVICE_ADD_4G_CAR||originType ==DEVICE_ADD_TYPE_QRCODE_SCAN){
            requestPermission();
        }
    }

    public void setToolBarVisibility(int visibility) {
        backButton.setVisibility(visibility);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] paramArrayOfInt) {
        super.onRequestPermissionsResult(requestCode, permissions, paramArrayOfInt);
        if (requestCode == AddFragmentTabActivity.PERMISSON_REQUESTCODE) {
            if (!PermissionUtil.verifyPermissions(paramArrayOfInt)) {      //没有授权
                TGLog.d(TAG, "onRequestPermissionsResult = false");
            }else{
                TGLog.d(TAG, "onRequestPermissionsResult = true");
            }
        }
    }

    private void requestPermission() {
        PermissionUtil permissionUtil = new PermissionUtil(AddFragmentTabActivity.this);
        permissionUtil.checkPermissions(AddFragmentTabActivity.this, AddFragmentTabActivity.PERMISSON_REQUESTCODE, AddFragmentTabActivity.needQrcodeScanPermissions);
    }

    @Override
    public void onNoSoundBtnForDevice() {
        if (originType == DEVICE_ADD_4G_CAR||originType == DEVICE_ADD_TYPE_QRCODE_SCAN||originType == DEVICE_ADD_4G_CAR_SEARCH){
            Reset4gCarGuideFragment reset4gCarGuideFragment = Reset4gCarGuideFragment.newInstance(originType);
            reset4gCarGuideFragment.setOnAddDeviceListener(this);
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fl_lan_add_container, reset4gCarGuideFragment,
                            "Reset4gCarGuideFragment").commit();
        }
    }

    @Override
    public void onClickBtnForDevice() {
        if (backButton.getVisibility() != View.VISIBLE) {
            backButton.setVisibility(View.VISIBLE);
        }
        if (originType == DEVICE_ADD_TYPE_QRCODE) {
            LogUtils.matTrackCustomKVEvent(this, "device_add", "QR");
            QRCodeAddFragment qrCodeAddFragment = new QRCodeAddFragment();
            qrCodeAddFragment.setListener(this);
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fl_lan_add_container, qrCodeAddFragment,
                            QRCodeAddFragment.TAG).commitAllowingStateLoss();
        } else if (originType == DEVICE_ADD_TYPE_AP || originType == DEVICE_ADD_TYPE_AP_LOCAL) {
            LogUtils.matTrackCustomKVEvent(this, "device_add", "ADA");
            ApSearchFragment apSearchFragment = new ApSearchFragment();
            apSearchFragment.setListener(this);
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fl_lan_add_container, apSearchFragment,
                            ApSearchFragment.TAG).commitAllowingStateLoss();
        } else if (originType == DEVICE_ADD_TYPE_LAN) {
            LogUtils.matTrackCustomKVEvent(this, "device_add", "CC");
            LanSearchFragment lanSearchFragment = new LanSearchFragment();
            lanSearchFragment.setListener(this);
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fl_lan_add_container, lanSearchFragment,
                            LanSearchFragment.TAG).commitAllowingStateLoss();
        } else if (originType == DEVICE_ADD_TYPE_QRCODE_SCAN || originType == DEVICE_ADD_4G_CAR) {
            if (originType == DEVICE_ADD_TYPE_QRCODE_SCAN && !StringUtils.isEmpty(mThirdPartyUUID) && mThirdPartyUUID.length() == 12){
                onDeviceConnecting(mThirdPartyUUID, AddFragmentTabActivity.TYPE_SCAN_QRCODE);
            }else{
                // TODO: 这个要对接新的扫码模块，不要自己重新写一个页面x
                LogUtils.matTrackCustomKVEvent(this, "device_add", "4G");

            }
        }else if (originType == DEVICE_ADD_4G_CAR_SEARCH) {
            AddSearchDeviceFragment searchDeviceFragment = new AddSearchDeviceFragment();
            searchDeviceFragment.setListener(this);
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fl_lan_add_container, searchDeviceFragment,
                            "searchDeviceFragment").commitAllowingStateLoss();

        }
    }

    @Override
    public void onSearchDevice(Bundle args) {
        args.putInt(EXT_DEVICE_ADD_TYPE, originType);
        SearchConnectFragment searchConnectFragment = SearchConnectFragment.newInstance(args);
        searchConnectFragment.setListener(this);
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fl_lan_add_container, searchConnectFragment,
                        SearchConnectFragment.TAG).commitAllowingStateLoss();
        hideLoading();
    }

    @Override
    public void onSearchDeviceBegin() {
        showLoading(getString(R.string.find_device));
    }

    @Override
    public void onSearchFailed() {
        hideLoading();
        LogUtils.matTrackCustomKVEvent(this, "event_add", "有线添加搜索失败");
    }

    @Override
    public void onSetDeviceName(long device, String uuid, int authStatus, String iccId,int freeCombo) {
        onAddDeviceReport();
        mFreeCombo = 0;
        if (originType == DEVICE_ADD_4G_CAR||originType == DEVICE_ADD_TYPE_QRCODE_SCAN||originType == DEVICE_ADD_4G_CAR_SEARCH){
            setCarDeviceName(device, uuid, authStatus, iccId,freeCombo);
        }else{
            hideLoading();
            backButton.setVisibility(View.GONE);
            this.uuid = uuid;
            this.deviceId = device;
            int authStatus1 = (originType == DEVICE_ADD_TYPE_QRCODE_SCAN) ? authStatus : 0;
            SetDeviceNameFragment setDeviceNameFragment = SetDeviceNameFragment.newInstance(device, uuid, authStatus1, iccId);
            setDeviceNameFragment.setListener(this);
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fl_lan_add_container, setDeviceNameFragment,
                            SearchConnectFragment.TAG).commitAllowingStateLoss();
        }

    }

    private void setCarDeviceName(long device, String uuid, int authStatus, String iccId,int freeCombo) {
        Intent intent = new Intent(getBaseContext(), ApSetNameActivity.class);
        intent.putExtra(ApiUrl.DEVICEID, device);
        intent.putExtra(ApiUrl.DEVICE_UUID, uuid);
        intent.putExtra(ApiUrl.DEVICE_AUTH, authStatus);
        intent.putExtra(ApiUrl.DEVICE_TYPE, DeviceTypeHelper.DEVICE_DRSIM);
        intent.putExtra(ApiUrl.DEVICE_ICCID, iccId);
        intent.putExtra(EXT_SIM_FREE_COMBO,freeCombo);
        startActivity(intent);
        finish();
    }

    @Override
    public void onFinish(boolean isApLocal) {
        Intent intent = new Intent();
        if (!isApLocal) {
            intent.setClass(getBaseContext(), DeviceListActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            if (originType == DEVICE_ADD_TYPE_QRCODE_SCAN && mFreeCombo ==0) {
                intent.putExtra(EXT_DEVICE_ADD_QRCODE_SUCCEDD_ID, this.deviceId);
                intent.putExtra(ApiUrl.DEVICE_UUID, uuid);
                if (originType == DEVICE_ADD_4G_CAR || originType == DEVICE_ADD_4G_CAR_SEARCH){
                    intent.putExtra(ApiUrl.DEVICE_TYPE, DeviceTypeHelper.DEVICE_DRSIM);
                }else{
                    intent.putExtra(ApiUrl.DEVICE_TYPE, DeviceTypeHelper.DEVICE_SIM);
                }
            }
        }
        startActivity(intent);
        finish();
    }

    @Override
    public void onApSearchLoading() {
        backButton.setEnabled(false);
    }

    @Override
    public void onBackPressed() {
        TGLog.d(TAG, "onBackPressed");
        finish();
    }


    @Override
    public void onGenerateQRCode(String ssi, String pwd, String uuid) {
        QRCodeImageFragment qrCodeImageFragment = QRCodeImageFragment.newInstance(ssi, pwd, uuid, DeviceTypeHelper.DEVICE_WIFI);
        qrCodeImageFragment.setListener(this);
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fl_lan_add_container, qrCodeImageFragment,
                        SearchConnectFragment.TAG).commitAllowingStateLoss();
    }

    @Override
    public void onDeviceConnecting(String random, int type) {
        uuid = random;

        if (originType == DEVICE_ADD_4G_CAR||originType == DEVICE_ADD_TYPE_QRCODE_SCAN||originType == DEVICE_ADD_4G_CAR_SEARCH){
            if (!TextUtils.isEmpty(random)){
                DeviceAddReportBean bean = DeviceAddReport.getInstance().getReportBean();
                if (bean!=null){
                    bean.uuid = random;
                    DeviceAddReport.getInstance().setReportBean(bean);
                }
            }
            CarDeviceProgressFragment carDeviceProgressFragment = CarDeviceProgressFragment.newInstance(uuid, type, originType);
            carDeviceProgressFragment.setListener(this);
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fl_lan_add_container, carDeviceProgressFragment,
                            CarDeviceProgressFragment.TAG).commitAllowingStateLoss();
        }else{
            backButton.setVisibility(View.VISIBLE);
            ProgressFragment progressFragment = ProgressFragment.newInstance(uuid, type, originType);
            progressFragment.setListener(this);
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fl_lan_add_container, progressFragment,
                            ProgressFragment.TAG).commitAllowingStateLoss();

        }

    }

    @Override
    public void onAddDeviceFailed(int type) {
        onAddDeviceReport();
        backButton.setVisibility(View.GONE);
        if (shouldSetStatusBarColor()) {
            backButton.post(() -> setStatusBarColor());
        }


        ActivityHelper.gotoAddFailedActivity(this, null, uuid, false);

    }
    private void onAddDeviceReport(){
        DeviceAddReportBean  bean = DeviceAddReport.getInstance().getReportBean();
        if (bean!=null){
            bean.connectLoadEnd  = System.currentTimeMillis();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        WiFiScanManager.scanner().resetDeviceNetWork(this);
        TGThreadPool.execute(() -> {
            if (!CameraHub.getInstance().isEnableLocalApConnect()){
                String curWifi = WifiToolkit.getCurWifi();
                BizWiFiUtil.removeDeviceWifi();
                WiFiScanManager.scanner().addNetworkWifi(curWifi);
            }
        });

    }
}
